<template>
    <div :class="['uploadBox', {'boxWidth': !isManyImg}]">
      <div class="demo-upload-list" v-for="item in uploadList">
        <template v-if="item.url">
          <img :src="IMG_SEE + item.url">
          <div class="demo-upload-list-cover">
            <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
          </div>
        </template>
        <template v-else>
          <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
        </template>
      </div>
      <Upload
        ref="upload"
        :show-upload-list="false"
        :default-file-list="defaultList"
        :on-success="handleSuccess"
        :on-error="handleError"
        :format="['jpg','jpeg','png']"
        :max-size="1024"
        :on-format-error="handleFormatError"
        :on-exceeded-size="handleMaxSize"
        :before-upload="handleBeforeUpload"
        type="drag"
        :headers="{'Authorization': $store.getters.token ? $store.getters.token : B_TOKEN}"
        :action="IMG_UPLOAD"
        :class="['uploadItem', {'Uposition': !isManyImg}]">                                                                                                                                                        
        <div :class="['imgItem', {'imgBg': !isManyImg}]">
          <div v-show="isShow">
              <Icon type="image" size="28" class="uploadImgIcon"></Icon>
              <span class="imgText">选择图片</span>
              <!-- <Button type="info" class="uploadImgBtn">

                <Icon type="plus-round"></Icon>上传
              </Button> -->
          </div>
         
          <!-- <Icon type="camera" size="20" v-show="isShow"></Icon> -->

          <!-- 仅在单张的时候显示 -->
          <span class="Icon">
            <Icon type="ios-eye-outline" size="20" @click.stop.native="handleView(imgName)"></Icon>
            <Icon type="ios-trash-outline" size="20" @click.stop.native="handleRemove(imgName)"></Icon>
          </span>
        </div>
      </Upload>
      <Modal title="查看图片" v-model="visible">
        <img :src="IMG_SEE + imgName" v-if="visible" style="width: 100%">
        <div slot="footer"></div>
      </Modal>
    </div>
</template>

<script>
  import {IMG_UPLOAD, IMG_SEE} from '@/service/api';
  export default {
    props: {
      value: {
        type: String,
        default: ''
      },
      isManyImg: {   //是否多张图片
        type: Boolean,
        default: false
      },
      num: {  //最多上传图片的个数
        type: Number,
        default: 3
      },
      imgList: {  //修改信息显示图片是传的图片id
        type: Array
      }
    },
    data () {
      return {
        B_TOKEN: this.$utils.Storage.getItem('B_TOKEN'),  //token
        // f_token: '1b67b1c1da99e6307c22042fc0b1708424b6b3857138d13b578ad46126d593ad',
        IMG_UPLOAD: IMG_UPLOAD,
        IMG_SEE: IMG_SEE,
        defaultList: [],
        imgName: '',
        visible: false,
        uploadList: [],
        uploadListArr: [],
        isShow: true  //单张是否显示上传按钮
      }
    },
    mounted() {
      this.uploadList = this.$refs.upload.fileList;
    },
    methods: {
      init() {  //修改信息时父组件调用方法显示图片,imgList = [{'url': 'id'}]
        if(this.imgList){
          // console.log(this.imgList)
          this.uploadList = this.imgList;  //显示图片

          this.update = true;  //执行该方法的皆为修改信息操作

          if(this.isManyImg){  //多张
            
            this.$refs.upload.fileList = this.uploadList;  //移除图片，新增图片时，数据同步

            for (let elem of this.uploadList.values()) {   //移除图片，新增图片，触发父组件返回数据同步
              this.uploadListArr.push(elem.url);
            }
          }else{  //单张
            this.imgName = this.uploadList[0].url;
            this.isShow = false;
          }
        }
      },
      handleView (name) {  //查看图片
        this.imgName = name;
        this.visible = true;
      },
      handleRemove (file) {  //移除图片
        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);

        if(!this.update){  //修改信息不应直接执行数据库删除（在确定修改之前）
          this.delImgFun(file.url);
        }

        if(this.isManyImg) {  //多张

          this.uploadListArr.splice(this.uploadListArr.indexOf(file.url), 1);  //用于返回的数据
          
          if(this.update){  //修改多张图片
            this.uploadList.forEach((item,index)=>{  //修改信息，uploadList的数据格式（被改变）只能使用循环遍历删除---用于显示

              if(item.url == file.url) this.uploadList.splice(index, 1)
            })
          }
          // console.log(this.uploadListArr)
          this.$emit('getPhoto', this.uploadListArr);

        }else{   //单张

          if(this.$refs.upload.fileList == 0){  //只有单击了--垃圾桶--删除才会出现为空的情况，此时才需要出现显示上传按钮

            this.uploadList = [];
            this.isShow = true;
          }
          this.$emit('getPhoto');
        }
        // this.delImgFun(file);
      },
      delImgFun(idOld) {  //从数据库删除
        if(idOld) {
          this.$ajax(this.$api.common.delImgUrl,{id: idOld}, (res)=> {
            // console.log(res.data)
          }, (data)=> {
            // console.log(data)
          })
        }
      },
      handleSuccess (res, file) {  //上传成功
        let id = res.info;
        file.url = id;
        this.imgName = id;

        if(!this.isManyImg){  //单张

          if(this.imgName){  //单张图片imgName存在说明上传过图片，此时应删掉现存的

            this.handleRemove(this.imgName)
            this.uploadList = [file];
          }
          // if(this.uploadList){
          this.isShow = false;
          // }
          this.$emit('input', id);
          this.$emit('getPhoto', id);
        }else {  //多张

          this.uploadList = this.$refs.upload.fileList;
          this.uploadListArr.push(id);
          console.log(this.uploadListArr)
          this.$emit('getPhoto', this.uploadListArr);
        }
      },
      handleError(error, file, fileList) {  //上传
        // console.log(file)
        if(file.code == 401){
          this.$Message.warning('身份验证已过期，请刷新页面或重新登录！');
        }
        else{
          this.$Message.error('上传失败！');
        }
      },
      handleFormatError (file) {  //文件格式错误
        this.$Message.warning('仅支持上传JPG、PNG格式的图片');
      },
      handleMaxSize (file) {  //限制大小
        this.$Message.warning('仅支持上传JPG、PNG格式的图片，且大小不超过1M');
      },
      handleBeforeUpload () {  //文件的个数限制
        const check = this.uploadList.length < this.num;
        if (!check) {
          this.$Message.warning('最多只能上传' + this.num + '张图片');
        }
        return check;
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
@width: 120px;
@height: 80px;
  .boxWidth {
    width: @width;
    height: @height;
  }
  .uploadBox {
    position: relative;
    min-width: @width;
    min-height: @height;
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    .uploadItem {
        display: inline-block;
        width: @width;
          .imgItem {
            width: 100%;
            height: @height;
            line-height: @height;
            .Icon {
              display: none;
            }
            .imgText {
              display: inline-block;
              padding-top: 15px;
              font-size: 12px;
              color: @color-Sub;
            }
            .uploadImgIcon {
              position: absolute;
              text-align: center;
              left: 50%;
              margin-left: -12px;
              margin-top: 15px;
              color: @color-Sub;
            }
            .uploadImgBtn {
              width: 84px;
              height: 23px !important;
              line-height: 12px;
              font-size: 12px;
              margin-top: 28px;
              .ivu-icon {
                padding-right: 10px;
              }
            }
          }
          .imgBg:hover {
            background: rgba(255, 255, 255, 0.5);
          }
          .imgBg:hover .Icon {
            display: block;
          }
    }

    .Uposition {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      .ivu-upload-drag {
        height: 100%;
        background: rgba(240,241,245,0.32);
        border: 1px solid rgba(240,241,245,0.32);
      }
    }
    .demo-upload-list{
        display: inline-block;
        width: @width;
        height: @height;
        text-align: center;
        line-height: @height;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        margin-right: 4px;
      }
      .demo-upload-list img{
        width: 100%;
        height: 100%;
      }
      .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
        // z-index: 2
      }
      .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
      }
      .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
      }
  }
  

</style>
